from django.db import models
from django.contrib.contenttypes import generic
from django.contrib.contenttypes.models import ContentType
from django.utils.translation import ugettext_lazy as _
from satchmo_store.contact.models import Contact


class LocalContact(models.Model):
    """Contact model extension to store extra tryton info."""
    contact = models.OneToOneField(Contact, verbose_name=_('Base Contact'))

    vat_number = models.CharField(verbose_name=_('VAT Number'), max_length=30)

    def __unicode__(self):
        if self.vat_number:
            return u"%s [%s]" % (self.contact.full_name, self.vat_number)
        else:
            return u'%s' % self.contact.full_name

    class Admin: pass

    class Meta:
        verbose_name = _('LocalContact')
        verbose_name_plural = _('LocalContacts')


class ObjMapperManager(models.Manager):
    """Special manager."""

    def get_for_object(self, instance):
        """resolves the obj_mapper for a given model-instance"""
        content_type = ContentType.objects.get_for_model(instance.__class__)
        return self.get(content_type=content_type, object_id=instance.id)

    def get_for_tryton_id(self, tryton_id, model):
        content_type = ContentType.objects.get_for_model(model)
        return self.get(tryton_id = tryton_id, content_type = content_type)


class ObjMapper(models.Model):
    """Holds the relationship between a Satchmo object and a Tryton object."""

    date_created = models.DateTimeField(
        _('date created'), default=models.datetime.datetime.now(), null=False,
        blank=False)

    date_modified = models.DateTimeField(
        _('date modified'), default=models.datetime.datetime.now(),
        null=False, blank=False)

    is_dirty = models.BooleanField(default=True)

    tryton_id = models.PositiveIntegerField(
        _('Tryton Id'), null=True, blank=True)

    content_type = models.ForeignKey(ContentType, verbose_name='Content Type')

    object_id = models.PositiveIntegerField(_('Object Id'), db_index=True)

    object = generic.GenericForeignKey('content_type', 'object_id')

    objects = ObjMapperManager()


    class Meta:
        verbose_name = _('Object Mapper')
        verbose_name_plural = _('Object Mapper')
        ordering = ('content_type', )

    def __unicode__(self):
        return u'%s' % self.object
